package com.wy.util.security;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * 加密工具
 * @author WY
 *
 */
public class EncryptUtil {
	
	/**
	 * 字符串进行MD5算法加密
	 * @param str
	 * @param charSet
	 * @return
	 */
	public static final String getMD5Str(String str,String charSet) { //md5加密  
	    MessageDigest messageDigest = null;  
	    try {    
	        messageDigest = MessageDigest.getInstance("MD5");    
	        messageDigest.reset();   
	        if(charSet==null){  
	            messageDigest.update(str.getBytes());  
	        }else{  
	            messageDigest.update(str.getBytes(charSet));    
	        }             
	    } catch (NoSuchAlgorithmException e) {   
	    	e.getMessage();
	    } catch (UnsupportedEncodingException e) {   
	    	e.getMessage();
	    }    
	      
	    byte[] byteArray = messageDigest.digest();    
	    StringBuffer md5StrBuff = new StringBuffer();    
	    for (int i = 0; i < byteArray.length; i++) {                
	        if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)    
	            md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));    
	        else    
	            md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));    
	    }    
	    return md5StrBuff.toString();    
	} 
	
	/**
	 * 文件MD5加密
	 * @param file
	 * @return
	 */
	public static String getMD5File(File file){
		String md5Value = null;
		FileInputStream in = null;
		try {
			//得到文件流对象
			in = new FileInputStream(file);
			//得到文件读取、写入、映射和操作的通道
			FileChannel fc = in.getChannel();
			//将此通道文件区域全部映射到内存
			MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
			//得到MD5摘要对象
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			//使用指定的byteBuffer跟新摘要
			md5.update(byteBuffer);
			//得到hash值结果数组
			byte[] hashResult = md5.digest();
			//将二进制数组转换为十六进制字符串
			BigInteger bi = new BigInteger(1,hashResult);
			md5Value = bi.toString(16);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return md5Value;
	}
	
}
